import { useEffect, useState } from 'react';
import { throttle } from 'lodash';
/**
 * @description: 文本字体自适应大小
 * @param value 自适应内容
 * @param min 字体最小值(默认20px)
 * @param max 字体最大值(默认30px)
 * @param minWidth 视窗适配最小宽度(默认1280px)
 * @param maxWidth 视窗适配最大宽度(默认1440px)
 * @return {*}
 */
const AutoFont = ({
  value,
  min = 20,
  max = 30,
  minWidth = 1280,
  maxWidth = 1440,
  children,
  ...rest
}) => {
  const [fontSize, setFontSize] = useState();

  const getFontSize = () => {
    let winWidth = document.documentElement.clientWidth;
    setFontSize(
      winWidth <= minWidth
        ? min
        : winWidth >= maxWidth
        ? max
        : parseInt(
            ((winWidth - minWidth) / (maxWidth - minWidth)) * (max - min),
            10,
          ) + min,
    );
  };

  const windowResize = throttle(() => {
    getFontSize();
  }, 100);

  useEffect(() => {
    getFontSize();
    window.addEventListener('resize', windowResize);
    return () => {
      window.removeEventListener('resize', windowResize);
    };
  }, []);
  return (
    <span {...rest} style={{ fontSize: fontSize }}>
      {children || value}
    </span>
  );
};

export default AutoFont;
